package bar.dark.lee.stats;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.NetworkInfo.DetailedState;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.TextView;

public class StatsMonthActivity extends SuperActivity
{
	public static final String STATS_MONTH_DATA = "stats_month_data";
	
	private DBSQLite sql;
	private int [] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.YELLOW, Color.CYAN };
	private String [] names;
	private double[] values;
	private ArrayList<StatsMonthData> list;
	private StatsMonthData data;
	
	private ViewGroup graphLayout;
	
	private View leftDateButton;
	private View rightDateButton;
	private TextView dateTextView;
	
	private View statsMonthListButton;
	
	private String colunmName = "";
	
	private int year;
	private int month;
	private int date;
	
	private int inoutFlag;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setFindView();
		setClickListener();
		
		Intent intent = getIntent();
		
		inoutFlag = intent.getIntExtra(StatsActivity.STATS_MONTH_FLAG, -1);
		
		if (inoutFlag != -1)
		{
			setData(inoutFlag);
		}
	}

	private void setFindView()
	{
		setContentView(R.layout.stats_month_activity);
		
		graphLayout = (ViewGroup) findViewById(R.id.statsMonthGraphLayout);
		leftDateButton = findViewById(R.id.statsMonthDateLeftButton);
		rightDateButton = findViewById(R.id.statsMonthDateRightButton);
		dateTextView = (TextView) findViewById(R.id.statsMonthDateTextView);
		statsMonthListButton = findViewById(R.id.statsMonthListButton);
		
		Calendar cal = Calendar.getInstance();
		year = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH)+1;
		date = cal.get(Calendar.DAY_OF_MONTH);
		
		dateTextView.setText(year + "년 ");
	}

	private void setClickListener()
	{
		leftDateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startLeftMonthButton();
			}
		});
		
		rightDateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startRightMonthButton();
			}
		});
		
		statsMonthListButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(StatsMonthActivity.this, StatsMonthListActivity.class);
				intent.putExtra(STATS_MONTH_DATA, list);
				intent.putExtra(StatsActivity.STATS_MONTH_FLAG, inoutFlag);
				intent.putExtra(StatsActivity.SELECT_YEAR, year);
				startActivity(intent);
			}
		});
	}

	private void setData(int flag)
	{
		// 데이터를 셋팅 하기 전에 뷰를 전부 지워준다.
		if (graphLayout.getChildCount() > 0)
		{
			graphLayout.removeAllViews();
		}
		
		if (flag == StatsActivity.STATS_IN)
		{
			colunmName = "inmoney";
			setTitle("수입 월별");
		}
		else if (flag == StatsActivity.STATS_OUT)
		{
			colunmName = "outmoney";
			setTitle("지출 월별");
		}
		else if (flag == StatsActivity.STATS_BALANCE)
		{
			setTitle("잔액 월별");
		}
		
		new ShowDialog().execute(0);
	}

	private void setStatsData()
	{
		String[] titles = new String[1];
		titles[0] = "";
		
		ArrayList<double[]> xData = new ArrayList<double[]>();
		
		xData.add(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
		
		List<double[]> yData = new ArrayList<double[]>();
		double [] value = new double[list.size()];
		
		for (int i = 0; i < list.size(); i++)
		{
//			value[i] = list.get(i).getMoney();
			BigDecimal money = BigDecimal.ZERO;
			try 
			{
				money = new BigDecimal(list.get(i).getMoney());
			} catch (Exception e) {
//				BDUtil.showDialogFinish(this, "알림", "데이터 로딩에 실패했습니다.");
				continue;
			}
			
			value[i] = money.doubleValue();
		}
		
		yData.add(value);
		
		int [] colors = new int[]{Color.RED};
		PointStyle [] styles = new PointStyle[]{PointStyle.DIAMOND};
		
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setXTitle("월");
		renderer.setAxisTitleTextSize(20);
	    renderer.setLabelsTextSize(15);
	    renderer.setLabelsColor(Color.BLACK);
	    renderer.setPointSize(7f);
	    renderer.setXLabels(12);
	    renderer.setYLabels(10);
	    renderer.setMarginsColor(0xff5050);
	    renderer.setShowLegend(false);
	    renderer.setPanEnabled(false, false);
	    renderer.setZoomEnabled(false, false);
		
		for (int i = 0; i < styles.length; i++)
		{
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			r.setLineWidth(5);
			renderer.addSeriesRenderer(r);
		}
		
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		
		XYSeries series = new XYSeries(titles[0]);
		double[] xValue= xData.get(0);
	    double[] yValue = yData.get(0);
	    
	    for (int i = 0; i < xValue.length; i++)
		{
			series.add(xValue[i], yValue[i]);
		}
	    
	    dataset.addSeries(series);
		      
		View view = ChartFactory.getLineChartView(this, dataset, renderer);
		
		view.setBackgroundColor(0xffffff);
		
		graphLayout.addView(view);
	}

	private void getMonthData()
	{
		list = new ArrayList<StatsMonthData>();
		
		// 달 시작일 가져온다
    	SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    	int startDate = Integer.parseInt(pref.getString(BDConstents.START_DATE, "1"));
    	
    	String inQuery = "";
    	String outQuery = "";
    	
		if (inoutFlag == StatsActivity.STATS_IN)
		{
			String firstDate = "";
			String lastDate = "";
			
			for (int i = 0; i < 12; i++)
			{
				data = new StatsMonthData();
				
				if (startDate == 1)
				{
					firstDate = BDUtil.getDateDB(year, i+1, 00);
					lastDate = BDUtil.getDateDB(year, i+1, 32);
				}
				else
				{
					if (i == 0)
					{
						firstDate = BDUtil.getDateDB(year, 1, startDate);
						lastDate = BDUtil.getDateDB(year, 2, startDate-1);
					}
					if (i == 11)
					{
						firstDate = BDUtil.getDateDB(year, 12, startDate);
						lastDate = BDUtil.getDateDB(year+1, 1, startDate-1);
					}
					else
					{
						firstDate = BDUtil.getDateDB(year, i+1, startDate);
						lastDate = BDUtil.getDateDB(year, i+2, startDate-1);
					}
				}
				
				inQuery = "SELECT " + colunmName + " FROM in_out WHERE " + colunmName + " not in ('0') and date >= " +
						firstDate + " and date <= " +
						lastDate + " and type not in (" + 
						BDConstents.INOUT_TYPE + ", " +
						BDConstents.OUTIN_TYPE + ", " +
						BDConstents.MYBANK_INOUT_TYPE + 
						");";
				
				sql.selectMapTile(this, inQuery, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int moneyIdx = c.getColumnIndex(colunmName);
						
//						int money = 0;
						BigDecimal money = BigDecimal.ZERO;
						
						c.moveToFirst();
						for (int j = 0; j < c.getCount(); j++)
						{
//							money = money + Integer.parseInt(c.getString(moneyIdx));
							money = money.add(new BigDecimal(c.getString(moneyIdx)));
							c.moveToNext();
						}
						
						data.setMoney(money.toString());
					}
				});
				
				data.setMonth((i + 1) + " 월");
				list.add(data);
			}
		}
		else if (inoutFlag == StatsActivity.STATS_OUT)
		{
			String firstDate = "";
			String lastDate = "";
			
			for (int i = 0; i < 12; i++)
			{
				data = new StatsMonthData();
				
				if (startDate == 1)
				{
					firstDate = BDUtil.getDateDB(year, i+1, 00);
					lastDate = BDUtil.getDateDB(year, i+1, 32);
				}
				else
				{
					if (i == 0)
					{
						firstDate = BDUtil.getDateDB(year, 1, startDate);
						lastDate = BDUtil.getDateDB(year, 2, startDate-1);
					}
					if (i == 11)
					{
						firstDate = BDUtil.getDateDB(year, 12, startDate);
						lastDate = BDUtil.getDateDB(year+1, 1, startDate-1);
					}
					else
					{
						firstDate = BDUtil.getDateDB(year, i+1, startDate);
						lastDate = BDUtil.getDateDB(year, i+2, startDate-1);
					}
				}
				
				outQuery = "SELECT " + colunmName + ", postmoney FROM in_out WHERE " +
						"inmoney in ('0') and (outmoney not in ('0') or postmoney not in ('0')) and date >= " +
						firstDate + " and date <= " +
						lastDate + " and type not in (" + 
						BDConstents.INOUT_TYPE + ", " +
						BDConstents.OUTIN_TYPE + ", " +
						BDConstents.MYBANK_INOUT_TYPE + ") and category not in ('" + BDConstents.CATEGORY_POST_OUT + "') "
						+ "UNION ALL "
						+ "SELECT " + colunmName + 
						", postmoney FROM in_out WHERE date >= " +
						firstDate + " and date <= " +
						lastDate + " and category in ('" 
						+ BDConstents.CATEGORY_SUSUMONEY + "')";
				
				sql.selectMapTile(this, outQuery
						, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int moneyIdx = c.getColumnIndex(colunmName);
						int pmoneyIdx = c.getColumnIndex("postmoney");
						
//						int money = 0;
						BigDecimal money = BigDecimal.ZERO;
						
						c.moveToFirst();
						for (int j = 0; j < c.getCount(); j++)
						{
//							money = money + Integer.parseInt(c.getString(moneyIdx));
							money = money.add(new BigDecimal(c.getString(moneyIdx)));
							money = money.add(new BigDecimal(c.getString(pmoneyIdx)));
							c.moveToNext();
						}
						
						data.setMoney(money.toString());
					}
				});
				
				data.setMonth((i + 1) + " 월");
				list.add(data);
			}
		}
		else if (inoutFlag == StatsActivity.STATS_BALANCE)
		{
			String firstDate = "";
			String lastDate = "";
			
			for (int i = 0; i < 12; i++)
			{
				data = new StatsMonthData();
				
				BigDecimal baleanceMoney = BigDecimal.ZERO;
				
				if (startDate == 1)
				{
					firstDate = BDUtil.getDateDB(year, i+1, 00);
					lastDate = BDUtil.getDateDB(year, i+1, 32);
				}
				else
				{
					if (i == 0)
					{
						firstDate = BDUtil.getDateDB(year, 1, startDate);
						lastDate = BDUtil.getDateDB(year, 2, startDate-1);
					}
					if (i == 11)
					{
						firstDate = BDUtil.getDateDB(year, 12, startDate);
						lastDate = BDUtil.getDateDB(year+1, 1, startDate-1);
					}
					else
					{
						firstDate = BDUtil.getDateDB(year, i+1, startDate);
						lastDate = BDUtil.getDateDB(year, i+2, startDate-1);
					}
				}
				
				inQuery = "SELECT inmoney FROM in_out WHERE inmoney not in ('0') and date >= " +
						firstDate + " and date <= " +
						lastDate + " and type not in (" + 
						BDConstents.INOUT_TYPE + ", " +
						BDConstents.OUTIN_TYPE + ", " +
						BDConstents.MYBANK_INOUT_TYPE + 
						");";
				
				sql.selectMapTile(this, inQuery, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int moneyIdx = c.getColumnIndex("inmoney");
						
//						int money = 0;
						BigDecimal money = BigDecimal.ZERO;
						
						c.moveToFirst();
						for (int j = 0; j < c.getCount(); j++)
						{
//							money = money + Integer.parseInt(c.getString(moneyIdx));
							money = money.add(new BigDecimal(c.getString(moneyIdx)));
							c.moveToNext();
						}
						
						data.setMoney(money.toString());
					}
				});
				
				baleanceMoney = new BigDecimal(data.getMoney());
				
				outQuery = "SELECT outmoney, postmoney FROM in_out WHERE " +
						"inmoney in ('0') and (outmoney not in ('0') or postmoney not in ('0')) and date >= " +
						firstDate + " and date <= " +
						lastDate + " and type not in (" + 
						BDConstents.INOUT_TYPE + ", " +
						BDConstents.OUTIN_TYPE + ", " +
						BDConstents.MYBANK_INOUT_TYPE + ") and category not in ('"+ BDConstents.CATEGORY_POST_OUT + "') "
						+ "UNION ALL "
						+ "SELECT outmoney" + 
						", postmoney FROM in_out WHERE date >= " +
						firstDate + " and date <= " +
						lastDate + " and category in ('" 
						+ BDConstents.CATEGORY_SUSUMONEY + "')";
				
				sql.selectMapTile(this, outQuery
						, new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int moneyIdx = c.getColumnIndex("outmoney");
						int pmoneyIdx = c.getColumnIndex("postmoney");
						
//						int money = 0;
						BigDecimal money = BigDecimal.ZERO;
						
						c.moveToFirst();
						for (int j = 0; j < c.getCount(); j++)
						{
//							money = money + Integer.parseInt(c.getString(moneyIdx));
							money = money.add(new BigDecimal(c.getString(moneyIdx)));
							money = money.add(new BigDecimal(c.getString(pmoneyIdx)));
							c.moveToNext();
						}
						
						data.setMoney(money.toString());
					}
				});
				
				baleanceMoney = baleanceMoney.subtract(new BigDecimal(data.getMoney().toString()));
				
				data.setMoney(baleanceMoney.toString());
				data.setMonth((i + 1) + " 월");
				list.add(data);
			}
		}
	}
	
	private void startLeftMonthButton()
	{
		year--;
		
		BDUtil.startLeftDegrees(dateTextView).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
				dateTextView.setText(year + "년 ");
				setData(inoutFlag);
			}
		});
	}
	
	private void startRightMonthButton()
	{
		year++;
		
		BDUtil.startRightDegrees(dateTextView).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
				dateTextView.setText(year + "년 ");
				setData(inoutFlag);
			}
		});
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(StatsMonthActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				getMonthData();
				return 0;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				setStatsData();
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_STATS);
		startActivity(intent);
	}
}
